package cn.icanci.loopstack.ddk.common.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * ip 地址工具类
 * 
 * @author icanci
 * @since 1.0 Created in 2022/11/20 15:37
 */
public class IPUtils {

    /**
     * 获取主机地址
     */
    public static String getHostIpAddress() {
        String realIp = null;
        try {
            InetAddress address = InetAddress.getLocalHost();
            // 如果是回环网卡地址, 则获取ipv4地址
            if (address.isLoopbackAddress()) {
                address = getInet4Address();
            }
            realIp = address.getHostAddress();
        } catch (Exception e) {
            // no op
        }
        return realIp;
    }

    /**
     *  获取IPV4网络配置
     */
    private static InetAddress getInet4Address() throws SocketException {
        // 获取所有网卡信息
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ip = addresses.nextElement();
                if (ip instanceof Inet4Address) {
                    return ip;
                }
            }
        }
        return null;
    }

}